#include <unistd.h>
#include <sys/inotify.h>

#include "watcher.h"


/*	Directory Watcher
 *	. Args :
 *		- <dirname>	: the path of the directory to be watched
 *		- <callbakc>: a function called each time a file is created in <dirname>
 *	. Return :
 *		- -1: external error (see errno)
 *		- 0 : success
 *		- n : read
 */
int watcher( char * dirname, callback_t callback )
{
	int notify, watch;
	unsigned int n;
	struct inotify_event event;

	notify = inotify_init();
	if( notify == -1 )
		return -1;
	
	watch = inotify_add_watch( notify, dirname, IN_CREATE );
	if( watch == -1 )
		return -1;

	while( (n = read( notify, (void*)&event, IN_EVENT_SIZE )) == IN_EVENT_SIZE ) {
		if( (event.mask & IN_CREATE) && !(event.mask & IN_ISDIR) ) {
			if( callback( event.name ) ) {
				inotify_rm_watch( notify, watch );
				close( notify );
				return 0;
			}
		}
	}

	return n;
}

#ifdef DEBUG

#include <stdio.h>

int callback( char * file )
{
	printf("\t- new file : %s\n", file);
	return 0;
}

int main( int argc, char ** argv )
{
	int ret;
	if( argc != 2 ) {
		printf("Usage : %s <dir>\n", argv[0]);
	} else {
		printf("Trying to watch directory : %s\n", argv[1]);
		ret = watcher(argv[1], callback);
		switch( ret ) {
			case -1:
				perror("Inotify "); break;
			case 0:
				printf("Callback returned other than 0\n"); break;
			default:
				printf("Watcher returned %d\n", ret);
				perror("Error ? ");
		}
	}
	return 0;
} 
#endif
